//
//  DeviceTransferenceVC.m
//  KEREN
//
//  Created by MW on 2023/4/17.
//

#import "DeviceTransferenceVC.h"

@interface DeviceTransferenceVC ()
@property (nonatomic, strong)UIScrollView *scrollView;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, strong) NSMutableArray *textFliedArrM;
@property (nonatomic, strong) NSMutableArray *delArrM;
@end

@implementation DeviceTransferenceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"授权转让"];
    UILabel *tipsLbl = [UILabel setLblText:@"授权给其他人后，您将会失去绑定车辆身份资格，请谨慎操作" font:Font(12) withColor:Color_86898E inSubView:self.view];
    [tipsLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10 + NAVTOP_Height);
        make.left.offset(24);
        make.right.offset(-24);
    }];
    tipsLbl.numberOfLines = 0;
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20 + NAVTOP_Height + 40, DEVICE_WIDTH, DEVICE_HEIGHT - 10 - NAVTOP_Height - BottomSpance_height - 80)];
    [self.view addSubview:_scrollView];
    UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditing)];
    [_scrollView addGestureRecognizer:imageTap];
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    UITextField *textField = [UITextField setFlieldplaceholder:@"请输入授权手机号" Font:Font(16) borderColor:[UIColor clearColor]];
    textField.frame = CGRectMake(24, 0, DEVICE_WIDTH - 48, 56);
    [_scrollView addSubview:textField];
    textField.backgroundColor = Whire_Color;
    [self.textFliedArrM addObject:textField];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification"
                                              object:textField];
    textField.keyboardType = UIKeyboardTypeNumberPad;
    _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_scrollView addSubview:_addBtn];
    [_addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textField.mas_bottom).offset(16);
        make.width.offset(DEVICE_WIDTH - 48);
        make.left.offset(24);
        make.height.offset(56);
    }];
    _addBtn.backgroundColor = [UIColor clearColor];
    _addBtn.layer.cornerRadius = 25;
    _addBtn.clipsToBounds = YES;
    _addBtn.layer.borderWidth = 1;
    _addBtn.layer.borderColor = Color_86898E.CGColor;
    [_addBtn setImage:[UIImage imageNamed:@"add_gray_icon"] forState:UIControlStateNormal];
    [_addBtn addTarget:self action:@selector(updateUI) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *transferenceBtn = [UIButton setButtonWithTitle:@"授权转让" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
    [self.view addSubview:transferenceBtn];
    
    [transferenceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(58);
        make.bottom.offset(-BottomSpance_height);
    }];
    [transferenceBtn addTarget:self action:@selector(transference) forControlEvents:UIControlEventTouchUpInside];
}

-(void)transference{
    WEAKSELF
    NSMutableArray *phoneArrM = [NSMutableArray array];
    for (int i = 0; i < _textFliedArrM.count; i++) {
        UITextField *textField = _textFliedArrM[i];
        if(textField.text.length  < 11){
            [[KRAlartManager shareInstance] showErrorAlert:@"请输入正确手机号"];
            return;
        }
        [phoneArrM addObject:textField.text];
    }
    NSDictionary *parameters = @{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"target_phones":phoneArrM};
    [NetworkingTool POST:Device_auth_transfer parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            [[KRAlartManager shareInstance] showImageAlert:@"授权成功！" ishaveBtn:NO btnTitle:@"" decLbl:@"返回首页（3S）" withImageStr:@"success_img" isDown:YES WithDownCount:3 sucessBlock:^(BOOL isSucess) {
                if(isSucess){
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                }
            }];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)updateUI{
    for (UIView *view in _scrollView.subviews) {
        [view removeFromSuperview];
    }
    for (int i = 0; i < self.textFliedArrM.count + 1; i ++) {
        if(i < self.textFliedArrM.count){
            UITextField *textField = self.textFliedArrM[i];
            textField.frame = CGRectMake(24, 0 + i * (56 + 16), DEVICE_WIDTH - 48, 56);
            [_scrollView addSubview:textField];
            textField.tag = i;
            textField.backgroundColor = Whire_Color;
            UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [_scrollView addSubview:delBtn];
            [delBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(textField.mas_right).offset(-16);
                make.centerY.equalTo(textField);
                make.width.height.offset(40);
            }];
            [delBtn setImage:[UIImage imageNamed:@"Delete_icon"] forState:UIControlStateNormal];
            delBtn.tag = i;
            [delBtn addTarget:self action:@selector(delTextField:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            UITextField *textField = [UITextField setFlieldplaceholder:@"请输入授权手机号" Font:Font(16) borderColor:[UIColor clearColor]];
            textField.keyboardType = UIKeyboardTypeNumberPad;
            textField.frame = CGRectMake(24, i * (56 + 16), DEVICE_WIDTH - 48, 56);
            textField.backgroundColor = Whire_Color;
            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                        name:@"UITextFieldTextDidChangeNotification"
                                                      object:textField];
            [_scrollView addSubview:textField];
            
            _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [_scrollView addSubview:_addBtn];
            [_addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(textField.mas_bottom).offset(16);
                make.width.offset(DEVICE_WIDTH - 48);
                make.left.offset(24);
                make.height.offset(56);
            }];
            _addBtn.backgroundColor = [UIColor clearColor];
            _addBtn.layer.cornerRadius = 25;
            _addBtn.clipsToBounds = YES;
            _addBtn.layer.borderWidth = 1;
            _addBtn.layer.borderColor = Color_86898E.CGColor;
            [_addBtn setImage:[UIImage imageNamed:@"add_gray_icon"] forState:UIControlStateNormal];
            [_addBtn addTarget:self action:@selector(updateUI) forControlEvents:UIControlEventTouchUpInside];
            UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [_scrollView addSubview:delBtn];
            [delBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(textField.mas_right).offset(-16);
                make.centerY.equalTo(textField);
                make.width.height.offset(40);
            }];
            [delBtn setImage:[UIImage imageNamed:@"Delete_icon"] forState:UIControlStateNormal];
            delBtn.tag = i;
            [delBtn addTarget:self action:@selector(delTextField:) forControlEvents:UIControlEventTouchUpInside];
            [self.textFliedArrM addObject:textField];
            break;
        }
    }
    _scrollView.contentSize = CGSizeMake(DEVICE_WIDTH, (self.textFliedArrM.count + 2) * (56 + 16));
}

- (void)delTextField:(UIButton *)sender{
    if(self.textFliedArrM.count == 1){
        [[KRAlartManager shareInstance] showErrorAlert:@"转让手机号不能小于1个"];
        return;
       // [KRAlartManager shareInstance] showAlert:@"转让s"
    }
    for (UITextField *textField in self.textFliedArrM) {
        if(textField.tag == sender.tag){
            [self.textFliedArrM removeObject:textField];
            break;
        }
    }
    for (UIView *view in _scrollView.subviews) {
        [view removeFromSuperview];
    }
    //[_scrollView removeAllSubviews];
    for (int i = 0; i < self.textFliedArrM.count; i ++) {
        UITextField *textField = self.textFliedArrM[i];
        textField.frame = CGRectMake(24, 0 + i * (56 + 16), DEVICE_WIDTH - 48, 56);
        [_scrollView addSubview:textField];
        textField.tag = i;
        textField.backgroundColor = Whire_Color;
        if(i == self.textFliedArrM.count - 1){
            _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [_scrollView addSubview:_addBtn];
            [_addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(textField.mas_bottom).offset(16);
                make.width.offset(DEVICE_WIDTH - 48);
                make.left.offset(24);
                make.height.offset(56);
            }];
            _addBtn.backgroundColor = [UIColor clearColor];
            _addBtn.layer.cornerRadius = 25;
            _addBtn.clipsToBounds = YES;
            _addBtn.layer.borderWidth = 1;
            _addBtn.layer.borderColor = Color_86898E.CGColor;
            [_addBtn setImage:[UIImage imageNamed:@"add_gray_icon"] forState:UIControlStateNormal];
            [_addBtn addTarget:self action:@selector(updateUI) forControlEvents:UIControlEventTouchUpInside];
        }
        if(self.textFliedArrM.count > 1){
            UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [_scrollView addSubview:delBtn];
            [delBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(textField.mas_right).offset(-16);
                make.centerY.equalTo(textField);
                make.width.height.offset(40);
            }];
            [delBtn setImage:[UIImage imageNamed:@"Delete_icon"] forState:UIControlStateNormal];
            delBtn.tag = i;
            [delBtn addTarget:self action:@selector(delTextField:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
}
-(void)endEditing{
    [self.view endEditing:YES];
}


-(void)textFiledEditChanged:(NSNotification*)notification{
    UITextField *textField = notification.object;
    NSString *str = textField.text;
    if(str.length > 11){
        str =  [str substringToIndex:11];
    }
    textField.text = str;
}


- (NSMutableArray *)textFliedArrM{
    if(!_textFliedArrM){
        _textFliedArrM = [NSMutableArray array];
    }
    return _textFliedArrM;
}
@end
